﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QFlow.Data;
using QFlow.Core;

namespace QFlow.Windows.Forms
{
    public static class AccountingManager
    {
        private static QFlowDbContext _Context;

        public static QFlowDbContext Context
        {
            get
            {
                return _Context;
            }
            set
            {
                _Context = value;
            }
        }

        public static void AddPayment(double amount, Account account)
        {
            account.Amount += amount;
            UserChangeCredit();
        }

        public static void WithdrawPayment(double amount, Account account)
        {
            account.Amount -= amount;
            UserChangeCredit();
        }

        public static void ResetCredit()
        {
            Account cashir = Context.Accounts.GetCashirAccount();
            Context.Accounts.GetSafeAccount().Amount += cashir.Amount;
            cashir.Amount = 0;

            Accounting.PurchaseCredit = 0;
            Accounting.PurchaseReturn = 0;
            Accounting.SalesCredit = 0;
            Accounting.SalesReturn = 0;

            LogUserResetCredit();
        }


        //Private

        private static void UserChangeCredit()
        {
            Data.AccountingLog log = new Data.AccountingLog()
            {
                CashirCredit = Context.Accounts.GetCashirAccount().Amount,
                SafeCredit = Context.Accounts.GetSafeAccount().Amount,
                PurchaseCredit = Accounting.PurchaseCredit,
                PurchaseReturn = Accounting.PurchaseReturn,
                SalesCredit = Accounting.SalesCredit,
                SalesReturn = Accounting.SalesReturn,
                TimeStamp = DateTime.Now,
                User = Context.Users.GetCurrentUser(),
                AccountingEvent = Context.AccountingEvents.GetChangeCreditEvent()
            };

            Context.AccountingLogs.InsertOnSubmit(log);
            Context.SubmitChanges();
        }

        private static void LogUserResetCredit()
        {
            Data.AccountingLog log = new Data.AccountingLog()
            {
                CashirCredit = 0,
                SafeCredit = Context.Accounts.GetSafeAccount().Amount,
                PurchaseCredit = 0,
                PurchaseReturn = 0,
                SalesCredit = 0,
                SalesReturn = 0,
                TimeStamp = DateTime.Now,
                User = Context.Users.GetCurrentUser(),
                AccountingEvent = Context.AccountingEvents.GetResetEvent()
            };

            Context.AccountingLogs.InsertOnSubmit(log);
            Context.SubmitChanges();
        }
    }
}
